// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: qiang

#pragma once

namespace coin2::exchange::mercado::order_v4 {

inline std::string GetExchangeOrderErrorCode(
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json) {
  if (json.HasMember("code")) {
    return json["code"].GetString();
  } else {
    return {};
  }
}

inline std::string GetExchangeOrderErrorMsg(
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json) {
  if (json.HasMember("message")) {
    return json["message"].GetString();
  } else {
    return {};
  }
}

inline coin::proto::OrderErrorCode GetOrderErrorCode(
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json_error_code,
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json_error_msg) {
  using coin::proto::OrderErrorCode;
  auto result = coin::proto::OrderErrorCode::ORDER_UNKNOWN_ERROR;
  std::string error_code = json_error_code.GetString();
  std::string error_msg = json_error_msg.GetString();
  if (error_msg == "API temporarily disabled" || error_code == "API_UNAVAILABLE") {
    result = OrderErrorCode::ORDER_API_ERROR;
  } else if (error_msg == "Insufficient balance to carry out the operation" || error_code == "INSUFFICIENT_BALANCE") {
    result = OrderErrorCode::SUBMIT_ORDER_INSUFFICIENT_FUND;
  } else if (error_msg == "Invalid number of decimal places entered" || error_code == "INVALID_DECIMAL_PLACES") {
    result = OrderErrorCode::SUBMIT_ORDER_WRONG_PRICE;
  } else if (error_msg == "This order have already been processed or canceled" || error_msg == "ORDER_PROCESSED") {
    result = OrderErrorCode::ORDER_CANCELED_ALREADY;
  } else if (error_msg == "Request denied: high request rate or invalid request" || error_code == "REQUEST_DENIED") {
    result = OrderErrorCode::API_LIMIT_ERROR;
  } else {
    LOG(ERROR) << "[GetOrderErrorCode] " << json_error_code.GetString() << ", " << error_msg;
  }

  return result;
}

}  // namespace coin2::exchange::mercado::order_v1
